﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;

namespace FrontEnd.Utilties.Text
{
	public class CyrillicToLatinTransliterator : ITransliterator
	{
		private const string NotCharSymbol = "_";
		private Dictionary<char, string> dictionary = new Dictionary<char, string>
		{
			{'а', "a"},
			{'б', "b"},
			{'в', "v"},
			{'г', "g"},
			{'д', "d"},
			{'е', "e"},
			{'ё', "jo"},
			{'ж', "zh"},
			{'з', "z"},
			{'и', "i"},
			{'й', "jj"},
			{'к', "k"},
			{'л', "l"},
			{'м', "m"},
			{'н', "n"},
			{'о', "o"},
			{'п', "p"},
			{'р', "r"},
			{'с', "s"},
			{'т', "t"},
			{'у', "u"},
			{'ф', "f"},
			{'х', "h"},
			{'ц', "ts"},
			{'ч', "ch"},
			{'ш', "sh"},
			{'щ', "shh"},
			{'ь', ""},
			{'ы', "y"},
			{'ъ', ""},
			{'э', "eh"},
			{'ю', "ju"},
			{'я', "ja"},
		};

		public string Transliterate(string text)
		{
			StringBuilder transliteratedTextBuilder = new StringBuilder();
			string previousTransliteration = string.Empty;

			foreach (char ch in text.ToCharArray())
			{
				string currentTransliteration = GetTransliteration(ch);
				if (previousTransliteration == NotCharSymbol && currentTransliteration == NotCharSymbol)
					continue;

				transliteratedTextBuilder.Append(currentTransliteration);
				previousTransliteration = currentTransliteration;
			}

			return transliteratedTextBuilder.ToString();
		}

		private string GetTransliteration(char ch)
		{
			CultureInfo cultureInfo = CultureInfo.GetCultureInfo("ru-ru");
			char key = Char.ToLower(ch, cultureInfo);

			if (dictionary.ContainsKey(key))
				return dictionary[key];

			if (Char.IsLetterOrDigit(ch))
				return ch.ToString();

			return NotCharSymbol;
		}
	}
}
